<script setup>
import PageContainer from '@/components/PageContainer/index.vue'
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores'
import { userUpdatePassService } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const {
  user: { username, nickname, email, id },
  setToken,
  setUser
} = useUserStore()

const formRenderer = ref()
onMounted(() => {
  formRenderer.value.updateForm({ username, nickname, email, id })
})

const checkOldSame = async (rule, value, cb) => {
  let params = formRenderer.value.getFormValue()
  if (value === params.old_pwd) {
    cb(new Error('原密码和新密码不能一样!'))
  } else {
    cb()
  }
}

const checkNewSame = async (rule, value, cb) => {
  let params = formRenderer.value.getFormValue()
  if (value !== params.new_pwd) {
    cb(new Error('新密码和确认再次输入的新密码不一样!'))
  } else {
    cb()
  }
}
const content = reactive([
  {
    type: 'input',
    id: 'old_pwd',
    label: '原密码',

    rules: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        pattern: /^\S{6,15}$/,
        message: '密码长度必须是6-15位的非空字符串',
        trigger: 'blur'
      }
    ]
  },
  {
    type: 'input',
    id: 'new_pwd',
    label: '新密码',

    rules: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      {
        pattern: /^\S{6,15}$/,
        message: '密码长度必须是6-15位的非空字符串',
        trigger: 'blur'
      },
      { validator: checkOldSame, trigger: 'blur' }
    ]
  },
  {
    type: 'input',
    id: 're_pwd',
    label: '确认新密码',

    rules: [
      { required: true, message: '请再次确认新密码', trigger: 'blur' },
      {
        pattern: /^\S{6,15}$/,
        message: '密码长度必须是6-15位的非空字符串',
        trigger: 'blur'
      },
      { validator: checkNewSame, trigger: 'blur' }
    ]
  }
])
const onSubmit = async () => {
  try {
    await formRenderer.value.methods.validate()
    let params = formRenderer.value.getFormValue()
    await userUpdatePassService(params)
    ElMessage({ type: 'success', message: '更换密码成功' })
    setToken('')
    setUser({})
    router.push('/login')

    console.log(params)
  } catch (error) {
    console.log(error)
  }
}
const onReset = () => {
  formRenderer.value.resetFields()
}
</script>

<template>
  <page-container title="基本资料">
    <el-row>
      <el-col :span="12">
        <el-form-renderer
          label-width="100px"
          :content="content"
          ref="formRenderer"
          style="padding-right: 30px"
          size="large"
        >
          <el-button @click="onSubmit" type="primary">修改密码</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-renderer>
      </el-col>
    </el-row>
  </page-container>
</template>

<style scoped></style>
